package wsi.gui.tool;

import java.io.File;
import java.util.HashSet;
import java.util.Set;

import javax.swing.JOptionPane;

import org.rygh.core.util.UIo;
import org.rygh.gui.model.callback.Callback;
import org.rygh.gui.model.callback.Returnback;
import org.rygh.gui.swing.common.view.SProgressGlass;
import org.rygh.gui.swing.presenter.SwingPresenter;
import org.rygh.gui.swing.window.SwingWindow;
import org.rygh.semantic.jena.SDatabase;
import org.rygh.semantic.model.ex.FactSet;
import org.rygh.semantic.model.rdf.Fact;
import org.rygh.semantic.model.rdf.Predicate;

import wsi.function.Function;
import wsi.gui.AppPresenter;
import wsi.script.AppConfig;

public class DBInjector {
	public final static String GENERATED_TRIPLES_FILE = "_debug_triples_generated.txt";

	private static File getFile(Function function) {
		return new File(AppConfig.shared().getFunctionsFolder(), String.format(
				"%s/%s/debug/%s", function.getService(), function.getName(),
				GENERATED_TRIPLES_FILE));
	}

	public static FactSet load(Function function, Predicate filter) {
		String content = UIo.readFile(getFile(function));

		FactSet factSet = new FactSet();
		factSet.setFilterPredicate(filter);
		factSet.loadJson(content);

		return factSet;
	}

	public static void save(Function function, String content) {
		UIo.saveFile(getFile(function), content);
	}

	private final SwingPresenter presenter;

	public DBInjector(SwingPresenter presenter) {
		this.presenter = presenter;
	}

	public void inject(final FactSet factSet) {
		SwingWindow window = presenter.getWindow();

		SProgressGlass<Void> progress = window.progress("Inserting...",
				new Callback<Void>() {
					@Override
					public void call(Void value) {
						if (presenter instanceof AppPresenter)
							((AppPresenter) presenter).setML(factSet.size()
									+ " facts inserted.");
					}
				});

		progress.setReturnback(new Returnback<Void>() {
			@Override
			public Void call() {
				SDatabase.shared().insert(factSet);
				return null;
			}
		});

		progress.run();
	}

	public void inject(final Function function) {
		FactSet factSet = load(function, null);

		Set<String> predSet = new HashSet<>();

		for (Fact fact : factSet)
			predSet.add(fact.getPredicate().getValue());

		String[] preds = predSet.toArray(new String[0]);

		SwingWindow window = presenter.getWindow();

		final String filter = (String) JOptionPane.showInputDialog(window,
				"Select a filtering predicate:", "Filtering Predicate",
				JOptionPane.QUESTION_MESSAGE, null, preds, preds[0]);

		if (filter == null)
			return;

		final Predicate filterPred = new Predicate(filter);

		FactSet facts = load(function, filterPred);

		inject(facts);

	}
}
